<template>
  <el-dialog
    v-model="dialogVisible"
    title="法律条款详情"
    width="80%"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="law-detail">
      <div v-if="lawData" class="detail-content">
        <!-- 基本信息 -->
        <div class="info-section">
          <h3 class="section-title">基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="条款ID">
              {{ lawData.id }}
            </el-descriptions-item>
            <el-descriptions-item label="法律代码">
              <span class="law-code">{{ lawData.lawCode }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="生效日期">
              {{ lawData.effectiveDate }}
            </el-descriptions-item>
            <el-descriptions-item label="最后更新">
              {{ lawData.updateTime }}
            </el-descriptions-item>
            <el-descriptions-item label="关联分类">
              <div v-if="relatedCategory" class="related-category">
                <el-tag type="info" size="small">
                  {{ relatedCategory.name }}
                </el-tag>
                <span class="category-desc">{{ relatedCategory.description }}</span>
              </div>
              <span v-else class="no-category">暂无关联分类</span>
            </el-descriptions-item>
            <el-descriptions-item label="关联文档">
              <div v-if="relatedDocument" class="related-document">
                <el-tag :type="getDocTypeTagType(relatedDocument.docType)" size="small">
                  {{ DOC_TYPES[relatedDocument.docType] }}
                </el-tag>
                <span class="doc-title">{{ relatedDocument.title }}</span>
              </div>
              <span v-else class="no-document">暂无关联文档</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 条款内容 -->
        <div class="info-section">
          <h3 class="section-title">条款内容</h3>
          <div class="content-container">
            <div class="content-text">
              {{ lawData.content }}
            </div>
          </div>
        </div>

        <!-- 关联文档详情 -->
        <div v-if="relatedDocument" class="info-section">
          <h3 class="section-title">关联文档信息</h3>
          <div class="document-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="文档标题">
                {{ relatedDocument.title }}
              </el-descriptions-item>
              <el-descriptions-item label="文档类型">
                <el-tag :type="getDocTypeTagType(relatedDocument.docType)">
                  {{ DOC_TYPES[relatedDocument.docType] }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="发布日期">
                {{ relatedDocument.publishDate }}
              </el-descriptions-item>
              <el-descriptions-item label="文档来源">
                {{ relatedDocument.source }}
              </el-descriptions-item>
              <el-descriptions-item label="关键词" v-if="relatedDocument.keywords">
                <div class="keywords">
                  <el-tag
                    v-for="keyword in getKeywords(relatedDocument.keywords)"
                    :key="keyword"
                    size="small"
                    style="margin-right: 5px; margin-bottom: 5px;"
                  >
                    {{ keyword }}
                  </el-tag>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- 关联分类详情 -->
        <div v-if="relatedCategory" class="info-section">
          <h3 class="section-title">分类信息</h3>
          <div class="category-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="分类名称">
                {{ relatedCategory.name }}
              </el-descriptions-item>
              <el-descriptions-item label="分类层级">
                第{{ relatedCategory.level }}级
              </el-descriptions-item>
              <el-descriptions-item label="分类描述" :span="2">
                {{ relatedCategory.description || '暂无描述' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">
                {{ relatedCategory.createTime }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑条款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { getLawDetail } from '../../../api/law'
import { getDocumentDetail, DOC_TYPES } from '../../../api/document'
import { getCategoryDetail } from '../../../api/category'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  lawId: {
    type: [Number, String],
    default: null
  }
})

const emit = defineEmits(['update:visible', 'edit'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加载状态
const loading = ref(false)

// 法律条款数据
const lawData = ref(null)

// 关联文档数据
const relatedDocument = ref(null)

// 关联分类数据
const relatedCategory = ref(null)

// 获取文档类型标签样式
const getDocTypeTagType = (docType) => {
  const typeMap = {
    0: 'danger',   // 法律 - 红色
    1: 'primary',  // 案例 - 蓝色
    2: 'warning',  // 判决书 - 橙色
    3: 'success'   // 文章 - 绿色
  }
  return typeMap[docType] || 'info'
}

// 处理关键词
const getKeywords = (keywords) => {
  if (!keywords) return []
  return keywords.split(',').filter(k => k.trim())
}

// 获取法律条款详情
const fetchLawDetail = async () => {
  if (!props.lawId) return
  
  loading.value = true
  try {
    const response = await getLawDetail(props.lawId)
    if (response.code === 200) {
      lawData.value = response.data
      
      // 如果有关联文档，获取文档详情
      if (response.data.documentId) {
        await fetchRelatedDocument(response.data.documentId)
      }
      
      // 如果有关联分类，获取分类详情
      if (response.data.categoryId) {
        await fetchRelatedCategory(response.data.categoryId)
      }
    } else {
      ElMessage.error('获取法律条款详情失败')
    }
  } catch (error) {
    console.error('获取法律条款详情失败:', error)
    ElMessage.error('获取法律条款详情失败')
  } finally {
    loading.value = false
  }
}

// 获取关联文档详情
const fetchRelatedDocument = async (documentId) => {
  try {
    const response = await getDocumentDetail(documentId)
    if (response.code === 200) {
      relatedDocument.value = response.data
    }
  } catch (error) {
    console.error('获取关联文档详情失败:', error)
  }
}

// 获取关联分类详情
const fetchRelatedCategory = async (categoryId) => {
  try {
    const response = await getCategoryDetail(categoryId)
    if (response.code === 200) {
      relatedCategory.value = response.data
    }
  } catch (error) {
    console.error('获取关联分类详情失败:', error)
  }
}

// 关闭对话框
const handleClose = () => {
  lawData.value = null
  relatedDocument.value = null
  relatedCategory.value = null
  emit('update:visible', false)
}

// 编辑法律条款
const handleEdit = () => {
  emit('edit', lawData.value)
  handleClose()
}

// 监听lawId变化，获取详情
watch(() => props.lawId, (newId) => {
  if (newId && props.visible) {
    fetchLawDetail()
  }
}, { immediate: true })

// 监听对话框打开
watch(() => props.visible, (visible) => {
  if (visible && props.lawId) {
    fetchLawDetail()
  }
})
</script>

<style scoped>
.law-detail {
  min-height: 300px;
}

.detail-content {
  padding: 0 10px;
}

.info-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.law-code {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.content-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.content-text {
  line-height: 1.8;
  font-size: 14px;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.related-document {
  display: flex;
  align-items: center;
  gap: 10px;
}

.related-category {
  display: flex;
  align-items: center;
  gap: 10px;
}

.doc-title {
  font-weight: 500;
  color: #333;
}

.category-desc {
  font-size: 12px;
  color: #666;
}

.no-document,
.no-category {
  color: #999;
  font-style: italic;
}

.document-info,
.category-info {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.keywords {
  line-height: 1.8;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  word-break: break-word;
}

/* 滚动条样式 */
.content-container::-webkit-scrollbar {
  width: 6px;
}

.content-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.content-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.content-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-content {
    padding: 0 5px;
  }
  
  .content-container {
    padding: 15px;
  }
  
  .related-document,
  .related-category {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  :deep(.el-descriptions) {
    --el-descriptions-item-bordered-label-background: #fafafa;
  }
}
</style>
